package com.studentManagement.servlet;

import com.baidu.translate.demo.TransApi;
import com.sun.org.apache.regexp.internal.RE;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@WebServlet(name = "APIServlet")
public class APIServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action=request.getParameter("action");
        if (action.equals("translateContext")){
            translateContext(request, response);//翻译功能
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    /**
    * 方法的功能描述：翻译功能
    * @params：【request,response】
    * @return:void */
    private void translateContext(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String context=request.getParameter("textarea").replaceAll("\n","。");
        String fromTo=request.getParameter("fromTo");
        //解析fromTo
        String from=fromTo.substring(0,fromTo.indexOf("-"));
        String to=fromTo.substring(fromTo.indexOf("-")+1,fromTo.length());

        // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
        final String APP_ID = "20171109000093865";
        final String SECURITY_KEY= "uWc5kImteqnShidlbib9";
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        PrintWriter out=response.getWriter();
        out.print(api.getTransResult(context, from, to));
//        System.out.println("from="+from+"--to="+to+"--context="+api.getTransResult(context, from, to));
    }
}
